import { ref } from 'vue'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/core'
import schema from '@/utils/vee-validate-schema'

export const useCountDown = (form, apifn) => {
  const formCom = ref(null)
  const time = ref(0)
  const { pause, resume } = useIntervalFn(
    () => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    },
    1000,
    { immediate: false }
  )
  const send = async () => {
    const valid = schema.mobile(form.mobile)
    if (valid === true) {
      // 通过
      if (time.value === 0) {
        // 没有倒计时才可以发送
        try {
          await apifn(form.mobile)
          time.value = 60
          resume()
          Message({
            type: 'success',
            text: '发送成功'
          })
        } catch (error) {
          Message(
            {
              type: 'error',
              text: `${error.response.data.message}`
            } || '发送失败'
          )
        }
      }
    } else {
      // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
      formCom.value.setFieldError(
        'mobile',
        valid
      )
    }
  }
  return { formCom, time, send }
}
